package cn.codenest;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * @author ：Hyman
 * @date ：Created in 2021/4/27 15:38
 * @description：
 * @modified By：
 * @version: $
 */
public class Client {

    private final String host;
    private final int port;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        Client client = new Client("127.0.0.1", 9988);
        client.start();
    }


    private void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture f = b.connect().sync();
            f.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }
    }


    @ChannelHandler.Sharable
    private class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

        /**
         * create by: Hyman
         * description: 当被通知channel是活跃的时候，发送一条消息,将在建立链接时被调用
         * create time: 2021/4/27
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channelActive");
            ctx.writeAndFlush(Unpooled.copiedBuffer("Hello world!", CharsetUtil.UTF_8));
        }

        /**
         * create by: Hyman
         * description:
         * (1)每当接受到数据时，都会调用这个方法
         * (2)从服务器发送的消息可能会被分块接受，如果服务器发送了5子节，也可能被分成两次，可能这个方法被调用了两次
         * create time: 2021/4/27
         */
        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuffer) throws Exception {
            System.out.println("channelRead0");
            System.out.println("Client received: " + byteBuffer.toString(CharsetUtil.UTF_8));
        }

        /**
         * create by: Hyman
         * description: 在读取操作期间，有异常抛出时调用
         * create time: 2021/4/27
         */
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
}
